<template>
  <!-- 策略管理 -->
  <template v-if="showType === 'page'">
    <div class="filterContent">
      <a-form :model="filterForm" layout="inline">
        <!-- <a-form-item label="电站名称">
          <a-select
            ref="select"
            v-model:value="filterForm.stationId"
            class="formInput"
            placeholder="请选择"
            show-search
            optionFilterProp="label"
            allow-clear
            style="width: 150px"
            @change="changeStation"
          >
            <a-select-option
              v-for="item in stationList"
              :key="item.stationId"
              :value="item.stationId"
              :label="item.stationName"
              :title="item.stationName"
            >
              {{ item.stationName }}
            </a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="电池堆名称">
          <a-select
            v-model:value="filterForm.linkDeviceId"
            class="formInput"
            placeholder="请选择"
            :disabled="!filterForm.stationId"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="item in energyLinkList"
              :value="item.deviceId"
              :key="item.deviceId"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="下发结果">
          <a-select
            v-model:value="filterForm.publishStatus"
            class="formInput"
            placeholder="请选择"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="item in ISSUANCE_STATUS"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="下发时间">
          <a-range-picker
            v-model:value="choseTime"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-space :size="10" style="margin-bottom: 20px">
          <a-button type="primary" class="filterBtn" @click="getStrategyPage"
            >查询</a-button
          >
          <a-button
            type="primary"
            class="yellowBtn"
            @click="goOther(1)"
            v-hasPermission="'strategySendMessage'"
            >信息下发</a-button
          >
          <!-- <a-upload
            v-model:file-list="fileList"
            class="upLoad"
            accept=".xlsx,.xls,.csv"
            :showUploadList="false"
            :maxCount="1"
            :action="handleImport"
            :beforeUpload="beforeUpload"
            ref="uploadRef"
            @change="handleUploadChange"
          >
            <a-button type="primary" class="greenBtn" :loading="importLoading"
              >导入</a-button
            >
          </a-upload> -->
        </a-space>
      </a-form>
    </div>
    <div class="tableContent" ref="tableContainerRef">
      <a-table
        :dataSource="tableData"
        :columns="columns"
        size="small"
        :pagination="false"
        :loading="tableLoading"
        :scroll="{ x: 'max-content', y: 'calc(100vh - 420px)' }"
        class="custom-table"
        style="width: 100%"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'publishStatus'">
            <a-tag
              :color="
                record.publishStatus === 2
                  ? 'green'
                  : record.publishStatus === 3
                  ? 'red'
                  : record.publishStatus === 1
                  ? 'orange'
                  : 'blue'
              "
              >{{ ISSUANCE_STATUS_OBJ[record.publishStatus] }}</a-tag
            >
          </template>
          <template v-if="column.key === 'remark'">
            <!-- <el-input
            v-if="record.edit"
            placeholder="请输入备注"
            v-model="record.remark"
            type="textarea"
            autosize
          ></el-input> -->
            <a-textarea
              v-model:value="record.remark"
              placeholder="请输入备注"
              allow-clear
              style="width: 100%"
              :autoSize="true"
              v-if="record.edit"
            />
            <span v-else>{{ record.remark }}</span>
          </template>
          <template v-if="column.key === 'handle'">
            <a-button
              type="link"
              @click="reissue(record)"
              v-if="record.publishStatus !== 2"
              style="padding: 4px 5px"
              v-hasPermission="'chargestrategyRemark'"
              >重新下发</a-button
            >
            <a-button
              v-hasPermission="'strategyRemark'"
              type="link"
              @click="handleEdit(record)"
              v-if="!record.edit"
              style="padding: 4px 5px"
              >备注</a-button
            >
            <a-button
              type="link"
              @click="save(record)"
              v-else
              style="padding: 4px 5px"
              >保存</a-button
            >
            <a-button
              type="link"
              @click="goDetial(record)"
              v-if="record.publishCommonEvent === 100"
              style="padding: 4px 5px"
              >详情</a-button
            >
            <a-popconfirm
              ok-text="确认"
              cancel-text="取消"
              @confirm="confirmDel(record)"
            >
              <template #title> 是否确定删除该记录? </template>
              <a-button
                v-hasPermission="'strategyDelete'"
                type="link"
                danger
                style="padding: 4px 5px"
                >删除</a-button
              >
            </a-popconfirm>
          </template>
        </template>
      </a-table>
      <a-pagination
        v-model:current="filterForm.current"
        v-model:page-size="filterForm.size"
        :total="total"
        position="bottomRight"
        show-size-changer
        @change="getStrategyPage"
        :show-total="(total) => `总共 ${total} 条`"
      >
        <template #buildOptionText="props">
          <span>{{ props.value }}条/页</span>
        </template>
      </a-pagination>
    </div>
  </template>
  <!-- 策略下发 -->
  <!-- <template v-else-if="showType === 'issued'">
    <Issued :stationList="stationList" @issuedGoBack="issuedGoBack" />
  </template> -->
  <template v-else>
    <StrategyPub
      :rowDataId="rowDataId"
      :stationList="stationList"
      :showType="showType"
      :stationId="filterForm.stationId"
      @issuedGoBack="issuedGoBack"
    />
  </template>
</template>
<script setup>

import {
  ISSUANCE_STATUS,
  ISSUANCE_STATUS_OBJ,
} from "@/constants/dispatchCenter.js"
import useTableScroll from "@/hooks/useTableScroll"
import StrategyPub from "@/views/DispatchCenter/Chargestrategy/components/strategyPub.vue"
import { chargestrategyConfigStore } from "@/stores/chargestrategyConfig"
const { changeNowStationAndLink } = chargestrategyConfigStore()
const $api = inject("$api")
const showType = ref("page")
const total = ref()
const props = defineProps({
  stationInfo: {
    type: Object,
  },
})

const filterForm = ref({
  stationId: null,
  linkDeviceId: null,
  publishStatus: null,
  startDate: "",
  endDate: "",
  size: 20,
  current: 1,
})
const choseTime = ref([])
//获取所有电站
const stationList = ref([])
const getStationList = async () => {
  const res = await $api.companyStationtList({})
  if (res && res.code === 0) {
    stationList.value = res.data
  }
}
//选中电站
const changeStation = (val) => {
  filterForm.value.linkDeviceId = null
  getEnergyLinkList(val)
}
//请求电池堆
const energyLinkList = ref([])
const getEnergyLinkList = async (id) => {
  const params = { stationId: id }
  const res = await $api.energyLinkList(params)
  if (res && res.code === 0) {
    energyLinkList.value = res.data
  }
}
//策略导入
const fileList = ref([])
const importLoading = ref(false)
// 导入
const handleImport = async (val) => {
  return "/api/monitor/charge/strategy/import"
}
const beforeUpload = () => {
  importLoading.value = true
}
const handleUploadChange = (data) => {
  const { file } = data
  if (file.status === "done") {
    message.success("导入成功")
    getStrategyPage()
    importLoading.value = false
  } else if (file.response) {
    message.error(`导入失败：${file.response?.msg}`)
    importLoading.value = false
  }
}
//获取策略列表分页
const columns = ref([
  {
    title: "电站名称",
    dataIndex: "stationName",
    key: "stationName",
    width: 220,
    align: "center",
    ellipsis: true,
    fixed: "left",
  },
  {
    title: "策略类型",
    dataIndex: "strategyTypeText",
    key: "strategyTypeText",
    width: 100,
    align: "center",
  },
  {
    title: "下发值",
    dataIndex: "publishValue",
    key: "publishValue",
    width: 100,
    align: "center",
  },
  {
    title: "电池堆名称",
    dataIndex: "linkName",
    key: "linkName",
    width: 100,
    align: "center",
  },
  {
    title: "下发人",
    dataIndex: "publishUserName",
    key: "publishUserName",
    width: 100,
    align: "center",
  },
  {
    title: "下发时间",
    dataIndex: "publishTime",
    key: "publishTime",
    width: 140,
    align: "center",
  },
  {
    title: "设备反馈时间",
    dataIndex: "feedbackTime",
    key: "feedbackTime",
    width: 140,
    align: "center",
  },
  {
    title: "下发结果",
    dataIndex: "publishStatus",
    key: "publishStatus",
    width: 100,
    align: "center",
  },
  {
    title: "设备反馈信息",
    dataIndex: "reason",
    key: "reason",
    width: 120,
    align: "center",
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    width: 120,
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "handle",
    key: "handle",
    width: 220,
    align: "center",
  },
])
const tableData = ref([])
const tableLoading = ref(false)
const getStrategyPage = async () => {
  tableLoading.value = true
  if (choseTime.value && choseTime.value.length) {
    filterForm.value.startDate = choseTime.value[0]
    filterForm.value.endDate = choseTime.value[1]
  } else {
    filterForm.value.startDate = ""
    filterForm.value.endDate = ""
  }
  const res = await $api.strategyPage(filterForm.value)
  if (res && res.code === 0) {
    tableData.value = res.data.records.map((item) => {
      item.edit = false
      return item
    })
    total.value = res.data.total
  }
  tableLoading.value = false
}
//重新下发
const reissue = async (data) => {
  const res = await $api.againPublish({ id: data.id })
  if (res && res.code === 0) {
    message.success("操作成功，具体结果请查看下发结果")
    getStrategyPage()
  }
}
//编辑备注
const editBefore = ref({})
const handleEdit = (row) => {
  row.edit = true
  if ("remark" in row) {
    editBefore.value = { id: row.id, remark: row.remark }
  } else {
    editBefore.value = { id: row.id, remark: "" }
  }
}
//保存备注
const save = async (row) => {
  row.edit = false
  let data = {
    id: row.id,
    remark: row.remark,
  }
  let res = await $api.strategyRemark(data)
  if (res.code === 0) {
    message.success("操作成功")
    getStrategyPage()
  }
}
//删除策略
const confirmDel = async (data) => {
  const res = await $api.strategyDelete({ id: data.id })
  if (res && res.code === 0) {
    message.success("删除成功")
    getStrategyPage()
  }
}
//返回
const issuedGoBack = () => {
  showType.value = "page"
  getStrategyPage()
}

//切换需量下发
const goOther = (e) => {
  switch (e) {
    case 1:
      return (showType.value = "Issued")
    case 2:
      return (showType.value = "Demand")

    default:
      return (showType.value = "page")
  }
}
//详情
const rowDataId = ref("")
const goDetial = (data) => {
  changeNowStationAndLink(data)
  rowDataId.value = data.id
  showType.value = "Issued"
}
watch(
  () => props.stationInfo,
  (val) => {
    console.log(val, val.id)
    if (val) {
      console.log(val, val.id)
      filterForm.value.stationId = val.id
      getStrategyPage()
    }
  }
)
onMounted(async () => {
  getStationList()
})
const handleChageStation = () => {
  filterForm.value.stationId = props.stationInfo.id
  getStrategyPage()
  changeStation(filterForm.value.stationId)
}
defineExpose({ handleChageStation })
</script>

<style lang="less" scoped>
.filterBtn {
  //margin-right: 10px;
}
.tableContent {
  border-radius: 4px;
  background-color: #141414;
  padding: 8px;
}
</style>
